﻿using System;
using System.Text;
using System.Windows.Forms;
using System.IO.Compression;
using System.Data;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Configuration;
using System.Xml;
using System.Collections.Generic;
using System.Diagnostics;
using Pub;


namespace Pub.Tools
{

    public static class MsgTools
    {

        /// <summary>
        /// 消息对话框
        /// </summary>
        /// <param name="txt">文本</param>
        /// <param name="title">标题</param>
        public static void InfoMsg(string txt)
        {

            MessageBox.Show(txt, "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        /// <summary>
        /// 错误对话框
        /// </summary>
        /// <param name="txt">文本</param>
        /// <param name="title">标题</param>
        public static void ErrorMsg(string txt)
        {

            MessageBox.Show(txt, " 错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

        }
        /// <summary>
        /// 问题对话框
        /// </summary>
        /// <param name="txt">文本</param>
        /// <param name="title">标题</param>
        public static bool QuestionMsg(string txt)
        {

            if (MessageBox.Show(txt, "确认请求", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                return true;
            }
            else
            {
                return false;
            }

        }
    }

    public static class SysTools
    {
        /// <summary>
        /// 生成GUID
        /// </summary>
        /// <returns></returns>
        public static string getGUID()
        {
            System.Guid guid = new Guid();
            guid = Guid.NewGuid();
            string str = guid.ToString();
            return str;
        }

        /// <summary>
        /// 将字符串转换为数字
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <param name="idefault">默认值</param>
        /// <returns>返回转换后的数字</returns>
        public static int ToInt(string strValue, int idefault)
        {
            int iResult = idefault;
            try
            {
                iResult = Convert.ToInt32(strValue);
            }
            catch
            {
            }
            return iResult;
        }

        public static int ToInt(char chrValue, int idefault)
        {
            int iResult = idefault;
            try
            {
                iResult = Convert.ToInt32(chrValue);
            }
            catch
            {
            }
            return iResult;
        }

        /// <summary>
        /// 将字符串转换为数字(默认为0)
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <returns>返回转换后的数字</returns>
        public static int ToInt(string strValue)
        {
            return ToInt(strValue, 0);
        }

        public static int ToInt(char chrValue)
        {
            return ToInt(chrValue, 0);
        }

        /// <summary>
        /// 将字符串转换为布尔值
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <returns>返回转换后的布尔值</returns>
        public static Boolean ToBoolean(string strValue)
        {
            Boolean bResult = false;
            try
            {
                bResult = Convert.ToBoolean(strValue);
            }
            catch
            {
            }
            return bResult;
        }

        /// <summary>
        ///  将字符串转换为日期
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <param name="dtime">默认日期</param>
        /// <returns>返回转换后的日期</returns>
        public static DateTime ToDateTime(string strValue, DateTime dtime)
        {
            DateTime dResult = dtime;
            try
            {
                dResult = Convert.ToDateTime(strValue);
            }
            catch
            {
            }
            return dResult;
        }

        public static string SpiltArr(string strArr, string strSplit, int intArr)
        {
            try
            {
                string strResult = string.Empty;
          //      string[] strArray = System.Text.RegularExpressions.Regex.Split(strArr, @"[" + strSplit + "]+");
                string[] strArray = System.Text.RegularExpressions.Regex.Split(strArr, strSplit);
                if (strArray.Length < (intArr + 1))
                {
                    return string.Empty;
                }
                strResult = strArray[intArr];
                return strResult;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        
        /// <summary>
        /// 获取当前机器的ip地址
        /// </summary>
        /// <returns>当前机器的ip地址</returns>
        public static string GetIPAddress()
        {
            try
            {

                string ipAddressStr = "";
                IPHostEntry entry = Dns.GetHostEntry("");
                foreach (IPAddress address in entry.AddressList)
                {
                    if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        ipAddressStr = address.ToString();
                        break;
                    }
                }
                return ipAddressStr;
            }
            catch
            {
                return "";
            }
        }


        public static string GetSysDir()
        {
            //return  Environment.GetEnvironmentVariable("windir");
            return System.Environment.GetFolderPath(System.Environment.SpecialFolder.System);
        }

        public static string GetCurrentDir()
        {
            return AppDomain.CurrentDomain.SetupInformation.ApplicationBase.ToString();
        }

        public static string GetTempDir()
        {

            //return System.Environment.GetFolderPath(System.Environment.SpecialFolder.Templates);
            return System.Environment.GetEnvironmentVariable("TEMP");
        }
        public static string GetDomainName()
        {
            string dn = Domain.GetComputerDomain().Name;
            return dn;
        }

        public static string GetVer()
        {
            return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
        }

        /// <summary>
        /// 获取目录所有相关文件名
        /// </summary>
        /// <param name="ListFiles"></param>
        /// <param name="strServerFileFolder"></param>
        /// <param name="strFileExtention"></param>
        /// <returns></returns>
        public static bool GetPathAllFiles(List<string> ListFiles, string strServerFileFolder, string strFileExtention)
        {
            /*********************************************************************************************
             *  功能:获取目录所有相关文件名
             *             List<string> ListFiles = new List<string>();//初始化 
             *             GetPathAllFiles(ListFiles, @"D:\Projects\MyAPP\exe\client", "xml");
             *             for (int i = 0; i < ListFiles.Count; i++)
             *                {
             *                   string a = ListFiles[i];
             *                   MessageBox.Show(a);
             *                 }            
             * 
             ***********************************************************************************************/

            try
            {
                DirectoryInfo dir = new DirectoryInfo(strServerFileFolder);
                //判断目录下是否存在文件,如果有则循环读取文件相关信息

                FileInfo[] finfo = dir.GetFiles("*" + strFileExtention);

                if (finfo.Length > 0)
                {
                    foreach (FileInfo f in finfo)
                    {
                        ListFiles.Add(f.FullName);
                    }
                }
                //判断目录下是否存在子目录,如果有则递归查询
                DirectoryInfo[] dinfo = dir.GetDirectories("*");
                if (dinfo.Length > 0)
                {
                    foreach (DirectoryInfo d in dinfo)
                    {
                        GetPathAllFiles(ListFiles, d.FullName, strFileExtention);
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                Console.Write(ex.ToString());
                return false;
            }
        }


        /// <summary>
        /// 写入系统日志
        /// </summary>
        /// <param name="LogTitle"></param>
        /// <param name="LogMess"></param>
        public static void WriteEventLog(string LogTitle, string LogMess)
        {
            try
            {
                EventLogTraceListener elt1 = new EventLogTraceListener(LogTitle);

                //Add the event log trace listener to collection


                //Remove the default listeren
                Trace.Listeners.RemoveAt(0);

                //Add the event log trace listener to the collection
                Trace.Listeners.Add(elt1);
                //Write output to the event log.
                Trace.WriteLine(LogMess);
            }
            catch
            {
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="txtFile">文件名</param>
        /// <param name="txtMess">内容</param>
        public static void WriteTxt(string txtFile, string txtMess)
        {
            try
            {
                string time = System.DateTime.Now.ToString();
                FileStream fst = new FileStream(txtFile, FileMode.Append);//追加模式
                StreamWriter stw = new StreamWriter(fst, System.Text.Encoding.GetEncoding("utf-8"));//指定编码.否则将出错!
                stw.WriteLine("[" + time + "]" + txtMess);
                stw.Close();
                fst.Close();
            }
            catch
            {
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="txtFile">文件名</param>
        /// <param name="txtMess">内容</param>
        public static void WriteTxt(string txtFile, string txtMess, FileMode fnmode)
        {
            try
            {
                string time = System.DateTime.Now.ToString();
                FileStream fst = new FileStream(txtFile, fnmode);//追加模式
                StreamWriter stw = new StreamWriter(fst, System.Text.Encoding.GetEncoding("utf-8"));//指定编码.否则将出错!
                if (fnmode == FileMode.Append)
                {
                    stw.WriteLine("[" + time + "]" + txtMess);
                }
                else
                {
                    stw.WriteLine(txtMess);
                }
                stw.Close();
                fst.Close();
            }
            catch
            {
            }
        }

    }

    public static class GridTools
    {
        /// <summary>  
        /// 保存DataGridView样式  
        /// </summary>  
        /// <param name="form">窗体</param>  
        /// <param name="dgv">DataGridView</param>  
        public static void SaveDGVStyle(Form form, DataGridView dgv)
        {
            try
            {
                string XMLPath;
                XMLPath = Application.StartupPath + @"/XML/";
                string fileName = XMLPath + form.Name + "_" + dgv.Name + ".xml";
                DataTable tb = new DataTable();
                tb.TableName = dgv.Name;
                tb.Columns.Add("colName");//列名  
                tb.Columns.Add("colHeader");//标题  
                tb.Columns.Add("colWidth");//宽度  
                tb.Columns.Add("colVisable");//是否显示  
                tb.Columns.Add("colDisplayIndex");//显示顺序  

                foreach (DataGridViewColumn col in dgv.Columns)
                {
                    DataRow row = tb.NewRow();
                    row["colName"] = col.Name;
                    row["colHeader"] = col.HeaderText;
                    row["colWidth"] = col.Width;
                    row["colVisable"] = col.Visible;
                    row["colDisplayIndex"] = col.DisplayIndex;
                    tb.Rows.Add(row);
                    tb.AcceptChanges();

                }
                tb.WriteXml(fileName);
            }
            catch (Exception ex)
            {
                MsgTools.ErrorMsg(ex.Message);
            }

        }

        /// <summary>  
        /// 读取DataGridView格式并应用  
        /// </summary>  
        /// <param name="form"></param>  
        /// <param name="dgv"></param>  
        public static void ReadGVStyle(Form form, DataGridView dgv)
        {
            try
            {
                string XMLPath;
                XMLPath = Application.StartupPath + @"/XML/";
                string fileName = XMLPath + form.Name + "_" + dgv.Name + ".xml";
                if (!File.Exists(fileName))
                    return;


                DataTable tb = new DataTable();
                tb.TableName = dgv.Name;
                tb.Columns.Add("colName");//列名  
                tb.Columns.Add("colHeader");//标题  
                tb.Columns.Add("colWidth");//宽度  
                tb.Columns.Add("colVisable");//是否显示  
                tb.Columns.Add("colDisplayIndex");//显示顺序  
                tb.ReadXml(fileName);
                foreach (DataRow row in tb.Rows)
                {
                    dgv.Columns[row["colName"].ToString()].HeaderText = row["colHeader"].ToString();
                    dgv.Columns[row["colName"].ToString()].Width = int.Parse(row["colWidth"].ToString());
                    dgv.Columns[row["colName"].ToString()].Visible = Boolean.Parse(row["colVisable"].ToString());
                    dgv.Columns[row["colName"].ToString()].DisplayIndex = int.Parse(row["colDisplayIndex"].ToString());

                }
            }
            catch (Exception ex)
            {
                MsgTools.ErrorMsg(ex.Message);
            }

        }

        private static string ConvertColumnNum2String(int columnNum)
        {
            if (columnNum > 26)
            {
                return string.Format("{0}{1}", (char)(((columnNum - 1) / 26) + 64), (char)(((columnNum - 1) % 26) + 65));
            }
            else
            {
                return ((char)(columnNum + 64)).ToString();
            }
        }

        /// <summary>
        /// 数据导出到EXCEL
        /// </summary>
        /// <param name="dgv"></param>
        public static void ExportToExcel(DataGridView dgv)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "保存为EXCEL文件";
            if (saveFileDialog.ShowDialog() != DialogResult.OK) { return; }

            try
            {
                Pub.Tools.ExcelApp ea = new Pub.Tools.ExcelApp();
                ea.New();
                StringBuilder sb = new StringBuilder();
                string columnTitle = "";



                //写入列标题
                for (int i = 0; i < dgv.ColumnCount; i++)
                {
                    if (!dgv.Columns[i].Visible) { continue; }
                    if (i > 0)
                    {
                        columnTitle += "\t";
                    }
                    columnTitle += dgv.Columns[i].HeaderText;

                    string range = string.Format("{0}1:{0}{1}", ConvertColumnNum2String(i + 1), (dgv.Rows.Count + 2).ToString());


                    ea.SetColumnWidth(range, dgv.Columns[i].Width / 8.5);
                    if (dgv.Columns[i].ValueType == typeof(System.String))
                    {
                        ea.SetNumberFormatLocal(range, "@");
                    }
                    string strAlignment = dgv.Columns[i].DefaultCellStyle.Alignment.ToString();
                    if (strAlignment.IndexOf("Left") > -1)
                    {
                        ea.SetHorisontalAlignment(range, 1);
                    }
                    if (strAlignment.IndexOf("Right") > -1)
                    {
                        ea.SetHorisontalAlignment(range, 2);
                    }
                    if (strAlignment.IndexOf("Center") > -1)
                    {
                        ea.SetHorisontalAlignment(range, 3);
                    }
                }
                sb.Append(columnTitle + "\r\n");

                //写入列内容
                for (int j = 0; j < dgv.Rows.Count; j++)
                {
                    string columnValue = "";
                    for (int k = 0; k < dgv.Columns.Count; k++)
                    {
                        if (!dgv.Columns[k].Visible) { continue; }
                        if (k > 0)
                        {
                            columnValue += "\t";
                        }
                        if (dgv.Rows[j].Cells[k].Value == null)
                            columnValue += "";
                        else
                        {
                            {
                                columnValue += dgv.Rows[j].Cells[k].Value.ToString().Trim();
                            }
                        }
                    }
                    sb.Append(columnValue + "\r\n");
                }

                ea.Paste("A1", sb.ToString());
                ea.SaveAs(saveFileDialog.FileName);
                ea.Visible = true;
                ea.Dispose();
            }
            catch (Exception e)
            {
                MsgTools.ErrorMsg(e.Message.ToString());
                return;
            }

            MsgTools.InfoMsg("数据导出EXCEL成功.\r\n" + saveFileDialog.FileName);
            saveFileDialog.Dispose();
        }

        /// <summary>
        /// 数据导出到文本文件
        /// </summary>
        /// <param name="dgv"></param>
        public static void ExportToTxt(DataGridView dgv)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "文本文件 (*.txt)|*.txt";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "保存为文本文件";
            if (saveFileDialog.ShowDialog() != DialogResult.OK) { return; }

            try
            {
                Stream myStream = saveFileDialog.OpenFile();
                StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
                string columnTitle = "";

                //写入列标题
                for (int i = 0; i < dgv.ColumnCount; i++)
                {
                    if (!dgv.Columns[i].Visible) { continue; }
                    if (i > 0)
                    {
                        columnTitle += "\t";
                    }
                    columnTitle += dgv.Columns[i].HeaderText;
                }
                sw.WriteLine(columnTitle);

                //写入列内容
                for (int j = 0; j < dgv.Rows.Count; j++)
                {
                    string columnValue = "";
                    for (int k = 0; k < dgv.Columns.Count; k++)
                    {
                        if (!dgv.Columns[k].Visible) { continue; }
                        if (k > 0)
                        {
                            columnValue += "\t";
                        }
                        if (dgv.Rows[j].Cells[k].Value == null)
                            columnValue += "";
                        else
                        {
                            columnValue += dgv.Rows[j].Cells[k].Value.ToString().Trim();
                        }
                    }
                    sw.WriteLine(columnValue);
                }
                sw.Close();
                myStream.Close();
            }
            catch (Exception e)
            {
                MsgTools.ErrorMsg(e.Message.ToString());
                return;
            }

            MsgTools.InfoMsg("数据导出成功.\r\n" + saveFileDialog.FileName);
            saveFileDialog.Dispose();
        }

        /// <summary>
        /// 数据导出到XML文件
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="dgvdt"></param>
        public static void ExportToXml(DataGridView dgv, DataTable dgvdt)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Xml files (*.xml)|*.xml";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "保存为xml文件";
            if (saveFileDialog.ShowDialog() != DialogResult.OK) { return; }

            DataTable dt = dgvdt.Copy();
            for (int k = 0; k < dgv.Columns.Count; k++)
            {
                if (dgv.Columns[k].Visible) { continue; }

                string ColumnName = dgv.Columns[k].Name.ToString();
                dt.Columns.Remove(dt.Columns[ColumnName]);
            }

            dt.WriteXml(saveFileDialog.FileName, XmlWriteMode.WriteSchema);
            dt.Dispose();
            MsgTools.InfoMsg("数据导出成功.\r\n" + saveFileDialog.FileName);
            saveFileDialog.Dispose();
        }

    }

    public static class DBClass
    {

        #region TreeView
        private static TreeNode FindNode(TreeNode tnParent, string strName)
        {
            if (tnParent == null) return null;

            if (tnParent.Tag.ToString() == strName) return tnParent;

            TreeNode tnRet = null;

            foreach (TreeNode tn in tnParent.Nodes)
            {

                tnRet = FindNode(tn, strName);

                if (tnRet != null) break;

            }

            return tnRet;

        }

        public static void MakeTree(string RootTag, string RootText, TreeView treeView, DataTable dt)
        {
            treeView.Nodes.Clear();
            TreeNode Node = new TreeNode();
            Node.Text = RootText;
            Node.Tag = RootTag;
            treeView.Nodes.Add(Node);
            AddTree(RootTag, treeView.Nodes[0], treeView, dt);

            treeView.Nodes[0].Expand();
            treeView.SelectedNode = treeView.Nodes[0];
        }

        private static void AddTree(string ParentID, TreeNode pNode, TreeView treeView, DataTable dt)
        {

            DataView dvTree = new DataView(dt);
            //过滤ParentID,得到当前的所有子节点
            //dvTree.RowFilter = "[PARENTID] = " + ParentID;

            string ID = dt.Columns[0].ColumnName;
            string ConText = dt.Columns[1].ColumnName;
            string Filter = string.Empty;
            if (dt.Columns.Count > 2)
            {
                Filter = dt.Columns[2].ColumnName;
                dvTree.RowFilter = "[" + Filter + "]=" + ParentID;
            }
            else
            {
                Filter = ID;
                Filter = "[" + Filter + "] like '" + ParentID + "%' and [" + Filter + "] <> '" + ParentID + "'";
                dvTree.RowFilter = Filter;
            }


            foreach (DataRowView Row in dvTree)
            {

                TreeNode Node = new TreeNode();
                string NodeText = string.Empty;
                if (dt.Columns.Count > 2)
                {
                    NodeText = Row[ConText].ToString();
                }
                else
                {
                    NodeText = string.Format("({0}){1}", Row[ID].ToString(), Row[ConText].ToString());
                }
                Node.Text = NodeText;
                Node.Tag = Row[ID].ToString();
                if (pNode == null)
                {    //添加根节点
                    treeView.Nodes.Add(Node);
                }
                else
                {
                    if (treeView.Nodes[0] != null)
                    {
                        TreeNode tnRet = FindNode(treeView.Nodes[0], Node.Tag.ToString());

                        if (tnRet == null)
                        {
                            //̀添加当前节点的子节点
                            pNode.Nodes.Add(Node);

                        }
                    }
                }
                AddTree(Row[ID].ToString(), Node, treeView, dt);     //再次递归

            }
        }

        #endregion TreeView


        /// <summary>
        /// DataTable转换为List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> DataTableToT<T>(DataTable dt)
        {
            List<T> lt = new List<T>();
            if (dt == null || dt.Rows.Count == 0)
            {
                return lt;
            }
            Type objType = typeof(T);
            foreach (DataRow dr in dt.Rows)
            {
                object obj = System.Activator.CreateInstance(objType);//创建实例  
                foreach (System.Reflection.PropertyInfo pi in objType.GetProperties())//遍历T类的所有属性  
                {
                    if (pi.PropertyType.IsPublic && pi.CanWrite && dt.Columns.Contains(pi.Name))//属性是否为public和可写  
                    {
                        object bojdr = dr[pi.Name];
                        if ((bojdr != DBNull.Value) && (bojdr != null))
                        {
                            Type pType = Type.GetType(pi.PropertyType.FullName);//属性类型 
                            object value = Convert.ChangeType(dr[pi.Name], pType);//转换dt值为对应属性的类型  
                            objType.GetProperty(pi.Name).SetValue(obj, value, null);//赋值  
                        }
                    }
                }
                lt.Add((T)obj);
            }
            return lt;
        } 


        public static DataTable SelectDB(DataTable dtsource, string filter)
        {
            DataRow[] drUserUrl = dtsource.Select(filter);
            DataTable dt = null;
            if (drUserUrl.Length > 0)
            {
                DataSet dsUserUrl = new DataSet();
                dsUserUrl.Merge(drUserUrl);
                dt = dsUserUrl.Tables[0];
            }
            else
            {
                dt = dtsource.Clone();   //复制表结构             
            }
            return dt;
        }


        /// <summary>
        /// 获取字符串中的首个Table名字
        /// </summary>
        /// <param name="strsql">SQL字符串</param>
        /// <returns>字符串中的首个Table名字</returns>
        public static string GetDBName(string strsql)
        {
            string strdb = strsql.Replace("\r\n", " ");
            strdb = strdb.Replace("\n\r", " ");
            string[] strArray = System.Text.RegularExpressions.Regex.Split(strdb, @"[ ]+");

            strdb = string.Empty;
            for (int ii = 0; ii < strArray.Length; ii++)
            {
                if (strArray[ii].ToLower() == "from".ToLower())
                {
                    //iEnd = ii + 1;
                    strdb = strArray[ii + 1];
                    break;
                }
            }

            if (strdb.Substring(0, 3).ToLower() == "dbo")
            {
                strdb = strdb.Substring(4, strdb.Length - 4);
            }
            //strArray = System.Text.RegularExpressions.Regex.Split(strdb, @"[.]+");

            //if (strArray.Length > 1)
            //{
            //    strdb = strArray[strArray.Length - 1];
            //}

            return strdb;
        }

        /// <summary>
        /// 获取字符串中的符合Table名字的字段
        /// </summary>
        /// <param name="strsql">SQL字符串</param>
        /// <param name="strdbname">Table名字</param>
        /// <returns>符合Table名字的字段字符串</returns>
        public static string GetFieldsName(string strsql, string strdbname, DataTable dt)
        {
            //DataTable dt = ;                      

            string strFields = strsql.Replace("\r\n", " ");

            strFields = strFields.Replace("\n\r", " ");
            string[] strArray = System.Text.RegularExpressions.Regex.Split(strFields, @"[ ]+");

            int iStart = 0;
            int iEnd = 0;
            strFields = string.Empty;
            for (int ii = 0; ii < strArray.Length; ii++)
            {
                if (strArray[ii].ToLower() == "select".ToLower())
                {
                    iStart = ii + 1;
                }
                if (strArray[ii].ToLower() == "from".ToLower())
                {
                    iEnd = ii - 1;
                    break;
                }
            }
            if (iEnd < iStart) { return string.Empty; }

            string[] strField = new string[100];
            int iPosField = 0;

            Boolean bl = strdbname.ToLower() == DBClass.GetDBName(strsql).ToLower();
            Boolean blas = false;
            for (int ii = iStart; ii <= iEnd; ii++)
            {

                string[] strtmp = System.Text.RegularExpressions.Regex.Split(strArray[ii], @"[,]+");

                string tmptb = strdbname + ".";

                for (int kk = 0; kk < strtmp.Length; kk++)
                {
                    if (blas)
                    {
                        blas = false;
                        kk++;
                        if (kk >= strtmp.Length)
                        {
                            break;
                        }
                    }
                    if (((strtmp[kk].ToLower().IndexOf(tmptb.ToLower()) == 0) || ((strtmp[kk].IndexOf(".") == -1) && (bl))) && (strtmp[kk].Length > 0))
                    {
                        if (strtmp[kk].ToLower() == "as")
                        {
                            blas = true;
                            break;
                        }
                        else
                        {
                            string strfn = strtmp[kk];
                            if (strtmp[kk].ToLower().IndexOf(tmptb.ToLower()) == 0)
                            {
                                strfn = strtmp[kk].Substring(tmptb.Length, strtmp[kk].Length - tmptb.Length);
                            }
                            if (strfn == "*")
                            {

                                return "*";

                            }
                            else
                            {
                                if (dt.Columns.Contains(strfn))
                                {
                                    if (!(Array.IndexOf<string>(strField, strfn) != -1)) //不存在
                                    {
                                        strField[iPosField] = strfn;
                                        iPosField++;
                                    }
                                    //strFields = strFields == string.Empty ? strfn : strFields + "," + strfn;
                                }
                            }
                        }

                    }
                }
            }
            strFields = string.Join(",", strField, 0, iPosField);
            return strFields;
        }

    }

    public static class ADTools
    {
        /// <summary>
        /// WINDOWS身份验证
        /// </summary>
        /// <param name="domain">AD域名</param>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="strMess">返回错误的信息</param>
        /// <returns>返回AD是否成功校验</returns>
        public static bool ADAuthUser(string domain, string userName, string password, ref string strMess)
        {
            bool isLogin = false;
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
            try
            {
                DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", domain), userName, password);
                entry.RefreshCache();
                isLogin = true;
                entry.Close();
            }
            catch (Exception ex)
            {
                strMess = ex.Message.ToString();
                isLogin = false;
            }
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
            return isLogin;
        }



        /// <summary>
        /// 更改Windows帐户密码
        /// </summary>
        /// <param name="domain">AD域名</param>
        /// <param name="username">用户名</param>
        /// <param name="oldPwd">旧密码</param>
        /// <param name="newPwd">新密码</param>
        /// <param name="strMess">返回错误的信息</param>
        /// <returns>返回是否成功更改Windows帐户密码</returns>
        public static Boolean ADChangeUserPasswd(string domain, string userName, string oldPwd, string newPwd, ref string strMess)
        {
            Boolean bl = ADAuthUser(domain, userName, oldPwd, ref  strMess);
            if (!bl) { return bl; }
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
            try
            {
                DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", domain), userName, oldPwd);
                entry.AuthenticationType = AuthenticationTypes.Secure;
                DirectorySearcher deSearch = new DirectorySearcher(entry);

                deSearch.Filter = "(&(objectClass=user) (SAMAccountName=" + userName + "))";//类型Type为user
                SearchResultCollection results = deSearch.FindAll();
                if (results.Count == 1)
                {
                    foreach (SearchResult OneSearchResult in results)
                    {
                        DirectoryEntry AlterUser = OneSearchResult.GetDirectoryEntry();

                        AlterUser.AuthenticationType = AuthenticationTypes.Secure;

                        AlterUser.Invoke("ChangePassword", new object[] { oldPwd, newPwd });
                        AlterUser.CommitChanges();
                        AlterUser.Close();
                    }
                }

                bl = true;
                results.Dispose();
                deSearch.Dispose();
                entry.Close();

            }
            catch (Exception ex)
            {
                bl = false;
                strMess = ex.Message.ToString();
            }
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
            return bl;
        }


        /// <summary> 
        /// 创建Windows帐户 
        /// </summary> 
        /// <param name="pathname"></param> 
        /// <returns></returns> 
        public static void CreateLocalUser(string username, string password, string description)
        {
            DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");

            var newUser = localMachine.Children.Add(username, "user");
            newUser.Invoke("SetPassword", new object[] { password });
            newUser.Invoke("Put", new object[] { "Description", description });
            newUser.CommitChanges();
            localMachine.Close();
            newUser.Close();
        }

        /// <summary> 
        /// 判断Windows用户是否存在 
        /// </summary> 
        /// <param name="username"></param> 
        /// <returns></returns> 
        public static bool ExistWinUser(string username)
        {
            try
            {
                using (DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"))
                {
                    var user = localMachine.Children.Find(username, "user");
                    return user != null;
                }
            }
            catch
            {
                return false;
            }
        }

        /// <summary> 
        /// 删除Windows用户 
        /// </summary> 
        /// <param name="username"></param> 
        /// <returns></returns> 
        public static bool DeleteWinUser(string username)
        {
            try
            {
                using (DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"))
                {
                    //删除存在用户 
                    var delUser = localMachine.Children.Find(username, "user");
                    if (delUser != null)
                    {
                        localMachine.Children.Remove(delUser);
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary> 
        /// 启用/禁用windows帐户 
        /// </summary> 
        /// <param name="username"></param> 
        public static void Disable(string username, bool isDisable)
        {
            var userDn = "WinNT://" + Environment.MachineName + "/" + username + ",user";
            DirectoryEntry user = new DirectoryEntry(userDn);
            user.InvokeSet("AccountDisabled", isDisable);
            user.CommitChanges();
            user.Close();
        }
    }

    public static class DESEncrypt
    {
        #region ========加密========

        private static string txtKey = "PatrixmszbP=";
        private static string txtIV = "Xmszbneagel=";

        /// <summary> 
        /// 加密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns>加密数据</returns> 
        public static string Encrypt(string Text)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray;
            inputByteArray = Encoding.Default.GetBytes(Text);
            //des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            //des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            des.Key = Convert.FromBase64String(txtKey);
            des.IV = Convert.FromBase64String(txtIV);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return ret.ToString();
        }

        #endregion

        #region ========解密========


        /// <summary> 
        /// 解密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns>解密数据</returns> 
        public static string Decrypt(string Text)
        {
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                int len;
                len = Text.Length / 2;
                byte[] inputByteArray = new byte[len];
                int x, i;
                for (x = 0; x < len; x++)
                {
                    i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
                    inputByteArray[x] = (byte)i;
                }
                //des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
                //des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
                des.Key = Convert.FromBase64String(txtKey);
                des.IV = Convert.FromBase64String(txtIV);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                return Encoding.Default.GetString(ms.ToArray());
            }
            catch
            {
                return Text;
            }
        }

        #endregion
    }

    public static class ZipString
    {

        /// <summary>
        /// 对字符串进行压缩
        /// </summary>
        /// <param name="str">待压缩的字符串</param>
        /// <returns>压缩后的字符串</returns>
        public static string CompressString(string str)
        {
            string compressString = "";
            byte[] compressBeforeByte = Encoding.GetEncoding("UTF-8").GetBytes(str);
            byte[] compressAfterByte = Compress(compressBeforeByte);
            //compressString = Encoding.GetEncoding("UTF-8").GetString(compressAfterByte);
            compressString = Convert.ToBase64String(compressAfterByte);
            return compressString;
        }
        /// <summary>
        /// 对字符串进行解压缩
        /// </summary>
        /// <param name="str">待解压缩的字符串</param>
        /// <returns>解压缩后的字符串</returns>
        public static string DecompressString(string str)
        {
            string compressString = "";
            //byte[] compressBeforeByte = Encoding.GetEncoding("UTF-8").GetBytes(str);
            byte[] compressBeforeByte = Convert.FromBase64String(str);
            byte[] compressAfterByte = Decompress(compressBeforeByte);
            compressString = Encoding.GetEncoding("UTF-8").GetString(compressAfterByte);
            return compressString;
        }


        /// <summary>
        /// 对byte数组进行压缩
        /// </summary>
        /// <param name="data">待压缩的byte数组</param>
        /// <returns>压缩后的byte数组</returns>
        public static byte[] Compress(byte[] data)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true);
                zip.Write(data, 0, data.Length);
                zip.Close();
                byte[] buffer = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(buffer, 0, buffer.Length);
                ms.Close();
                return buffer;

            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }


        /// <summary>
        /// 对byte数组进行解压
        /// </summary>
        /// <param name="data">待解压的byte数组</param>
        /// <returns>解压后的byte数组</returns>
        public static byte[] Decompress(byte[] data)
        {
            try
            {
                MemoryStream ms = new MemoryStream(data);
                GZipStream zip = new GZipStream(ms, CompressionMode.Decompress, true);
                MemoryStream msreader = new MemoryStream();
                byte[] buffer = new byte[0x1000];
                while (true)
                {
                    int reader = zip.Read(buffer, 0, buffer.Length);
                    if (reader <= 0)
                    {
                        break;
                    }
                    msreader.Write(buffer, 0, reader);
                }
                zip.Close();
                ms.Close();
                msreader.Position = 0;
                buffer = msreader.ToArray();
                msreader.Close();
                return buffer;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
    }

    public static class StringTools
    {
        /// <summary>
        /// 任意进制转换
        /// </summary>
        /// <param name="value"></param>
        /// <param name="fromBase"></param>
        /// <param name="toBase"></param>
        /// <returns></returns>
        public static string X2X(string value, int fromBase, int toBase)
        {
            return AnyRadixConvert.X2X(value, fromBase, toBase);
        }

        private static class AnyRadixConvert
        {
            private static char[] rDigits = 
            {
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 
                'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 
                'U', 'V', 'W', 'X', 'Y', 'Z'
            };

            /// <summary>
            /// 将指定基数的数字的 System.String 表示形式转换为等效的 64 位有符号整数。
            /// </summary>
            /// <param name="value">包含数字的 System.String。</param>
            /// <param name="fromBase">value 中数字的基数，它必须是[2,36]</param>
            /// <returns>等效于 value 中的数字的 64 位有符号整数。- 或 - 如果 value 为 null，则为零。</returns>
            private static long x2h(string value, int fromBase)
            {
                value = value.Trim();
                if (string.IsNullOrEmpty(value))
                {
                    return 0L;
                }

                string sDigits = new string(rDigits, 0, fromBase);
                long result = 0;
                //value = reverse(value).ToUpper(); 1
                value = value.ToUpper();// 2
                for (int i = 0; i < value.Length; i++)
                {
                    if (!sDigits.Contains(value[i].ToString()))
                    {
                        throw new ArgumentException(string.Format("The argument \"{0}\" is not in {1} system.", value[i], fromBase));
                    }
                    else
                    {
                        try
                        {
                            //result += (long)Math.Pow(fromBase, i) * getcharindex(rDigits, value[i]); 1
                            result += (long)Math.Pow(fromBase, i) * getcharindex(rDigits, value[value.Length - i - 1]);//   2
                        }
                        catch
                        {
                            throw new OverflowException("运算溢出.");
                        }
                    }
                }

                return result;
            }

            private static int getcharindex(char[] arr, char value)
            {
                for (int i = 0; i < arr.Length; i++)
                {
                    if (arr[i] == value)
                    {
                        return i;
                    }
                }
                return 0;
            }

            //long转化为toBase进制
            private static string h2x(long value, int toBase)
            {
                int digitIndex = 0;
                long longPositive = Math.Abs(value);
                int radix = toBase;
                char[] outDigits = new char[63];

                for (digitIndex = 0; digitIndex <= 64; digitIndex++)
                {
                    if (longPositive == 0) { break; }

                    outDigits[outDigits.Length - digitIndex - 1] =
                        rDigits[longPositive % radix];
                    longPositive /= radix;
                }

                return new string(outDigits, outDigits.Length - digitIndex, digitIndex);
            }

            //任意进制转换,将fromBase进制表示的value转换为toBase进制
            public static string X2X(string value, int fromBase, int toBase)
            {
                if (string.IsNullOrEmpty(value.Trim()))
                {
                    return string.Empty;
                }

                if (fromBase < 2 || fromBase > 36)
                {
                    throw new ArgumentException(String.Format("The fromBase radix \"{0}\" is not in the range 2..36.", fromBase));
                }

                if (toBase < 2 || toBase > 36)
                {
                    throw new ArgumentException(String.Format("The toBase radix \"{0}\" is not in the range 2..36.", toBase));
                }

                long m = x2h(value, fromBase);
                string r = h2x(m, toBase);
                return r;
            }
        }

        public static String[] StringToStrings(string strString)
        {
            return System.Text.RegularExpressions.Regex.Split(strString, @"[\r\n]+");
        }

        public static String StringsToString(string[] strString)
        {
            return string.Join("\r\n", strString, 0, strString.Length);
        }

        public static string TranTimeStr(int iTime)
        {
            TimeSpan ts = new TimeSpan(0, 0, iTime);
            string cTime = string.Empty;
            if (ts.Hours > 0)
            {
                cTime = string.Format("{0:D2}:{1:D2}:{2:D2} ", ts.Hours, ts.Minutes, ts.Seconds);
            }
            else
            {
                cTime = string.Format("{0:D2}:{1:D2} ", ts.Minutes, ts.Seconds);
            }
            if ((ts.Minutes == 0) && ((ts.Seconds == 0)))
            {
                cTime = "无";
            }
            return cTime;
        }
    }

    public static class XmlTools
    {
        /// <summary>
        /// 读取XML
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="strKey"></param>
        /// <param name="strDef"></param>
        /// <returns></returns>
        public static string Read(string FileName, string strKey, string strDef)
        {
            string strResult = strDef;
            XmlDocument doc = new XmlDocument();
            if (!File.Exists(FileName))
            {
                return strResult;
            }
            doc.Load(FileName);
            XmlNode xnserver = doc.SelectSingleNode(strKey);
            if (xnserver != null)
            {
                strResult = xnserver.InnerText;
            }

            return strResult;
        }

        /// <summary>
        /// 读取XML(默认文件)
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="strKey"></param>
        /// <returns></returns>
        public static string Read(string FileName, string strKey)
        {
            return Read(FileName, strKey, string.Empty);
        }


        private static void CreateXml(string FileName, string strKey)
        {
            XmlDocument doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
            doc.AppendChild(dec);

            string[] XmlArray = System.Text.RegularExpressions.Regex.Split(strKey, @"[/]+");

            XmlElement root = null;

            for (int i = 0; i < XmlArray.Length; i++)
            {
                XmlElement pxe = doc.CreateElement(XmlArray[i]);
                if (i == 0)
                {
                    doc.AppendChild(pxe);
                }
                else
                {
                    root.AppendChild(pxe);
                }
                root = pxe;

            }

            //            string xmlString = doc.OuterXml;
            doc.Save(FileName);

        }

        private static void TryAddNode(ref XmlDocument doc, string strKey)
        {

            string[] XmlArray = System.Text.RegularExpressions.Regex.Split(strKey, @"[/]+");


            for (int i = 0; i < XmlArray.Length; i++)
            {
                string strpkey = string.Join("/", XmlArray, 0, i + 1);
                XmlNode xnuser = doc.SelectSingleNode(strpkey);
                if (xnuser == null)
                {
                    XmlElement text = doc.CreateElement(XmlArray[i]);
                    doc.DocumentElement.LastChild.AppendChild(text);
                }

            }
            //       string xmlString = doc.OuterXml;

        }

        /// <summary>
        /// 保存XML
        /// </summary>
        /// <param name="FileName">文件名</param>
        /// <param name="strKey">Key</param>
        /// <param name="strResult">值</param>
        public static void Save(string FileName, string strKey, string strResult)
        {
            XmlDocument doc = new XmlDocument();
            if (!File.Exists(FileName))
            {
                CreateXml(FileName, strKey);
                //               return ;
            }
            doc.Load(FileName);
            XmlNode xnuser = doc.SelectSingleNode(strKey);
            if (xnuser == null)
            {
                TryAddNode(ref doc, strKey);
                xnuser = doc.SelectSingleNode(strKey);

            }
            xnuser.InnerText = strResult;
            doc.Save(FileName);
        }

        private static void CheckNodeAttrib(XmlDocument doc, XmlNode _node, string nodename)
        {
            if (_node.Attributes[nodename] == null)
            {
                XmlAttribute _nodeatt = doc.CreateAttribute(nodename);
                _node.Attributes.Append(_nodeatt);
            }
        }

        private static int GetRandom(int iUp)
        {
            Random ro = new Random();
            return ro.Next(iUp);
        }


        public static string GetRandomServiceURL(string strUrl)
        {
            string[] UrlArray = System.Text.RegularExpressions.Regex.Split(strUrl, @"[,]+");
            if (UrlArray.Length > 1)
            {
                strUrl = UrlArray[GetRandom(UrlArray.Length)];
            }
            return strUrl.ToLower();
        }

        public static string GetServiceURLList(string SysSetXml)
        {
            if (!File.Exists(SysSetXml))
            {
                return string.Empty;
            }

            string strUrl = string.Empty;

            string curip = SysTools.GetIPAddress();

            XmlDocument document = new XmlDocument();
            document.Load(SysSetXml);

            XmlNode XNUrl = document.SelectSingleNode("SysSet/ServiceURL");

            strUrl = XNUrl.ChildNodes[0].Attributes["url"].InnerText;

            //    XmlNodeList xl = XNUrl.ChildNodes;//读取所有节点
            for (int i = 1; i < XNUrl.ChildNodes.Count; i++)
            {
                XmlNode _node = XNUrl.ChildNodes[i];
                string url = _node.Attributes["url"].InnerText;
                string ip = _node.Attributes["ip"].InnerText;

                int ii = curip.IndexOf(ip, 0);
                if (ii == 0)
                {
                    strUrl = url;
                    break;
                }
                //if 
            }

            return strUrl.ToLower();
        }
    }

    public static class ConfigTools
    {

        /// <summary>
        /// 修改配置文件中某项的值
        /// </summary>
        /// <param name="key">appSettings的key</param>
        /// <param name="value">appSettings的Value</param>
        public static void SetConfig(string key, string value)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings[key] != null)
                config.AppSettings.Settings[key].Value = value;
            else
                config.AppSettings.Settings.Add(key, value);

            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }

        /// <summary>
        /// 读取配置文件某项的值
        /// </summary>
        /// <param name="key">appSettings的key</param>
        /// <returns>appSettings的Value</returns>
        public static string GetConfig(string key)
        {
            string _value = string.Empty;
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings[key] != null)
            {
                _value = config.AppSettings.Settings[key].Value;
            }
            return _value;
        }


    }

}
